<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}区域`"
    width="536"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[300px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import { overallOptions } from '@/api/public'

import { createRegion, updateRegion, regionDetail } from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
}

const rules = {
  region_name: [
    { required: true, message: '请输入区域名称', trigger: 'change' },
  ],
}

const form = ref()
const model = ref({})
const loading = ref()
const orderData = ref()
const optionsData = ref({})

onMounted(() => {
  getOption()
})

const getOption = async () => {
  const { data } = await overallOptions({
    params: ['map.logistics-api', 'map.channel'],
  })
  let _options = data['mapLogisticsApi']
  if (_options) {
    optionsData.value = data
  }
}

const fieldList = [
  {
    field: 'region_name',
    label: '区域名称',
  },
  {
    field: 'remark',
    label: '区域说明',
    type: 'textarea',
    autosize: { minRows: 8, maxRows: 8 },
  },
]

watch(
  () => props.id,
  val => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async id => {
  try {
    const { data } = await regionDetail({ id })

    model.value = {
      ...data,
    }
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    console.warn(formInfo)
    const api = {
      edit: updateRegion,
      add: createRegion,
    }
    const { id } = props

    const { logistics_api, channel, shipping } = formInfo
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
      logistics_api_id: logistics_api?.id,
      channel_id: channel?.channel_id,
      logistics_id: channel?.logistics_id,
      logistics_api_shipping_id: shipping?.id,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
